#pragma once

#include <iostream>
#include <string>
#include <functional>
#include <poll.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include "sock.hpp"

namespace poll_ns
{
    static const int defaultport = 8080;
    static const int num = 2048;
    static const int defaultfd = -1;

    using func_t = std::function<std::string(const std::string &)>;

    class PollServer
    {
    public:
        PollServer(func_t func, int port = defaultport) : _func(func), _port(port), _listensock(-1), _rfds(nullptr)
        {
        }
        void Print()
        {
            std::cout << "fd list: ";
            for (int i = 0; i < num; ++i)
            {
                if (_rfds[i].fd != defaultfd)
                    std::cout << _rfds[i].fd << " ";
            }

            std::cout << std::endl;
        }
        void Accepter(int listensock)
        {

            std::string clientip;
            uint16_t clientport = 0;
            int sock = Sock::Accept(_listensock, &clientip, &clientport); // accept = 等 + 获取
            if (sock < 0)
                return;
            // 开始进行服务器的处理逻辑
            logMessage(NOMAL, "accept success [%s:%d]", clientip.c_str(), clientport);

            int i = 0;
            for (; i < num; i++)
            {
                if (_rfds[i].fd != defaultfd)
                    continue;
                else
                    break;
            }
            if (i == num)
            {
                logMessage(WARING, "server is full,please wait");
                close(sock); // 服务器满了，直接关闭它
            }
            else
            {
                _rfds[i].fd = sock;
                _rfds[i].events = POLLIN;
                _rfds[0].revents = 0;
            }
        }
        void ReseItem(int pos)
        {
            _rfds[pos].fd = defaultfd;
            _rfds[pos].events = 0;
            _rfds[pos].revents = 0;
        }
        void Recver(int pos)
        {
            logMessage(DEBUG, "Recver in");

            // 这样读取是有问题的！数据读完了吗？？
            char buffer[1024];
            ssize_t s = recv(_rfds[pos].fd, buffer, sizeof(buffer) - 1, 0); // 这里在进行读取的时候，不会被阻塞。
            if (s > 0)
            {
                buffer[s] = 0;
                logMessage(NOMAL, "client: %s", buffer);
            }
            else if (s == 0)
            {
                close(_rfds[pos].fd);
                ReseItem(pos);
                logMessage(NOMAL, "client quit");
                return;
            }
            else
            {
                close(_rfds[pos].fd);
                ReseItem(pos);
                logMessage(ERROR, "client quit: %s", strerror(errno));
                return;
            }

            // 2.处理request
            std::string response = _func(buffer);

            // 3.返回response
            // write bug
            write(_rfds[pos].fd, response.c_str(), response.size());
            logMessage(DEBUG, "Recver end");
        }
        // 1.handler even中，不仅仅是有一个fd是就绪的，可能存在多个
        // 2.我们的select目前只处理了read事件
        void HandlerReadEvent()
        {
            for (int i = 0; i < num; ++i)
            {
                // 过滤掉非法的fd
                if (_rfds[i].fd == defaultfd)
                    continue;
                if (_rfds[i].events & POLLIN)
                {
                    logMessage(DEBUG, "HandlerReadEvent in");
                    // 正常的fd
                    // 正常的fd不一定就绪了
                    // ? 目前一定式listensock，只有一个
                    if (_rfds[i].fd == _listensock && (_rfds[0].revents == POLLIN))
                        Accepter(_listensock);
                    else if ((_rfds[i].revents & POLLIN))
                        Recver(i); // 处理正常的读取事件
                    else
                    {
                    }
                }
            }
        }
        void initServer()
        {
            _listensock = Sock::Socket();
            Sock::Bind(_listensock, _port);
            Sock::Listen(_listensock);

            _rfds = new struct pollfd[num];
            for (int i = 0; i < num; ++i)
            {
                ReseItem(i);
            }
            _rfds[0].fd = _listensock; // 不变了
            _rfds[0].events = POLLIN;
        }
        void start()
        {
            for (;;)
            {
                int timeout = -1;
                int n = poll(_rfds, num, timeout);
                switch (n)
                {
                case 0:
                    logMessage(NOMAL, "timeout...");
                    break;
                case -1:
                    logMessage(WARING, "poll error,code: %d,err string: %s", errno, strerror(errno));
                    break;
                default:
                {
                    logMessage(NOMAL, "have event read!");
                    HandlerReadEvent();
                }
                break;
                }
                Print();
            }
        }
        ~PollServer()
        {
            if (_listensock < 0)
                close(_listensock);
            if (_rfds)
                delete[] _rfds;
        }

    private:
        int _port;
        int _listensock;
        struct pollfd *_rfds;
        func_t _func;
    };
}